package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApUserSearch;
import com.heima.search.service.IApUserSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ApUserSearchServiceImpl implements IApUserSearchService {


    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 保存用户搜索历史记录
     *
     * @param keyword     关键字
     * @param userId      用户ID
     * @param equipmentId 设备ID
     */
    @Async
    @Override
    public void saveSearchRecord(String keyword, Integer userId, String equipmentId) {
        //1. 判断用户是否对当前关键字进行过搜索
        //1.1 构建查询对象
        Query query = new Query();
        if (userId != null) {
            query.addCriteria(Criteria.where("userId").is(userId));
        } else {
            query.addCriteria(Criteria.where("equipmentId").is(equipmentId));
        }
        query.addCriteria(Criteria.where("keyword").is(keyword));
        //1.2 获取数量
        long count = mongoTemplate.count(query, ApUserSearch.class);

        //2. 根据返回结果 如果null保存 存在：更新时间
        if (count == 0) {
            //2.1 构建搜索记录对象 执行保存
            ApUserSearch apUserSearch = new ApUserSearch();
            apUserSearch.setCreatedTime(new Date());
            apUserSearch.setUserId(userId);
            apUserSearch.setKeyword(keyword);
            apUserSearch.setEquipmentId(equipmentId);
            mongoTemplate.save(apUserSearch);
        } else {
            //存在：更新时间
            Update update = new Update();
            update.set("createdTime", new Date());
            mongoTemplate.updateFirst(query, update, "apUserSearch");
        }


        //TODO 将用户搜索关键字 存储到联想词集合中
    }


    /**
     * 从MoongoDB中获取用户最近5条搜索记录
     *
     * @param dto 入参
     * @return
     */
    @Override
    public ResponseResult load(ApArticleSearchDto dto) {
        //1.封装查询条件  用户ID或者设备ID；排序；前5条
        Query query = new Query();
        User user = UserThreadLocalUtil.get();
        if (user.getUserId() != null) {
            query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        } else {
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }
        //1.2设置分页 排序
        query.with(PageRequest.of(0, 5, Sort.Direction.DESC, "createdTime"));
        //2.执行查询
        List<ApUserSearch> list = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(list);
    }

    /**
     * 删除搜索记录（批量删除）
     *
     * @param dto 删除搜索文档DTO集合对象
     * @return
     */
    @Override
    public ResponseResult delete(ApArticleSearchDto dto) {
        //1.封装删除文档数据条件
        Query query = new Query();
        List<ApUserSearch> hisList = dto.getHisList();
        if (!CollectionUtils.isEmpty(hisList)) {
            List<String> collect = hisList.stream().map(ApUserSearch::getId).collect(Collectors.toList());
            query.addCriteria(Criteria.where("id").in(collect));
            //2. 执行删除
            mongoTemplate.remove(query, ApUserSearch.class);
        }
        return ResponseResult.okResult();
    }
}
